

const express = require('express');
const router = express.Router();
const userControll = require('../controllers/userControll');
const pool = require('../config/db'); // 导入数据库连接池
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { expressjwt: expressJwt } = require('express-jwt');
const jwtBlacklistControll = require('../controllers/jwtBlacklistControll');

const key = "Yangjunjwt123456"; // 秘钥

// 获取用户通过JWT中的ID
router.get('/profile', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
    try {
        const userId = req.auth.userId; // 从JWT中提取用户ID
        const user = await userControll.getUserById(userId);
        if (user) {
            res.json(user);
        } else {
            res.status(404).json({ message: '用户不存在' });
        }
    } catch (error) {
        if (error.name === 'UnauthorizedError') {
            // 将无效的 JWT 添加到黑名单中
            const token = req.headers.authorization.split(' ')[1];
            await jwtBlacklistControll.addTokenToBlacklist(token);
            res.status(401).json({ message: '未携带token或token失效' });
        } else {
            res.status(500).json({ message: error.message });
        }
    }
});

// 更新用户信息
router.put('/profile', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
    try {
        const userId = req.auth.userId; // 从JWT中提取用户ID
        const { username, email, password } = req.body;
        const user = await userControll.getUserById(userId);
        if (!user) {
            return res.status(404).json({ message: '用户不存在' });
        }
        await userControll.updateUser(userId, username, email, password);
        const updatedUser = await userControll.getUserById(userId);
        res.json(updatedUser);
    } catch (error) {
        if (error.name === 'UnauthorizedError') {
            // 将无效的 JWT 添加到黑名单中
            const token = req.headers.authorization.split(' ')[1];
            await jwtBlacklistControll.addTokenToBlacklist(token);
            res.status(401).json({ message: '未携带token或token失效' });
        } else {
            res.status(500).json({ message: error.message });
        }
    }
});

// 删除用户
router.delete('/profile', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
    try {
        const userId = req.auth.userId; // 从JWT中提取用户ID
        const user = await userControll.getUserById(userId);
        if (!user) {
            return res.status(404).json({ message: '用户不存在' });
        }
        await userControll.deleteUser(userId);
        res.json({ message: '用户已删除' });
    } catch (error) {
        if (error.name === 'UnauthorizedError') {
            // 将无效的 JWT 添加到黑名单中
            const token = req.headers.authorization.split(' ')[1];
            await jwtBlacklistControll.addTokenToBlacklist(token);
            res.status(401).json({ message: '未携带token或token失效' });
        } else {
            res.status(500).json({ message: error.message });
        }
    }
});

// 用户注册
router.post('/register', async (req, res) => {
    try {
        const { username, email, password } = req.body;

        // 检查是否已经存在同名用户或相同邮箱
        const [existingUser] = await pool.query('SELECT * FROM users WHERE username = ? OR email = ?', [username, email]);
        if (existingUser.length > 0) {
            return res.status(400).json({ message: '用户名或邮箱已存在' });
        }

        const result = await userControll.createUser(username, email, password);
        const userId = result.insertId;
        const newUser = await userControll.getUserById(userId);
        res.status(201).json(newUser);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// 用户登录
router.post('/login', async (req, res) => {
    try {
        const { email, password } = req.body;

        // 获取用户
        const [userRows] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
        const user = userRows[0];

        if (!user) {
            return res.status(400).json({ message: '用户不存在' });
        }

        // 验证密码
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
            return res.status(400).json({ message: '请输入正确的密码' });
        }

        // 生成 JWT
        const token = jwt.sign({ userId: user.user_id, username: user.username }, key, { expiresIn: '1h' });
        res.json({ token, message: '后台登录成功' });
      
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});
// router.post('/login', async (req, res) => {
//     try {
//         const { email, password } = req.body;

//         // 获取用户
//         const [userRows] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
//         const user = userRows[0];

//         if (!user) {
//             return res.status(400).json({ message: '用户不存在' });
//         }

//         // 验证密码
//         const isPasswordValid = await bcrypt.compare(password, user.password);
//         if (!isPasswordValid) {
//             return res.status(400).json({ message: '请输入正确的密码' });
//         }

//         // 生成 JWT
//         const token = jwt.sign({ userId: user.user_id, username: user.username }, key, { expiresIn: '1h' });
//         res.json({ token, username: user.username, message: '后台登录成功' });
//     } catch (error) {
//         res.status(500).json({ message: error.message });
//     }
// });

module.exports = router;
